package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author ZC
 * @since 2022-06-30
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {
    @Autowired
    private MinIOService minIOService;
    //注入  minIO
    @Override
    public ResponseResult saveWmMaterial(MultipartFile file) {
        User user = UserThreadLocalUtil.get();   //在拦截器中获取 user
        if (user == null) {
            //证明没有 登录人  直接返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            String url = minIOService.upload(file);

            WmMaterial wmMaterial = new WmMaterial();
            //wmMaterial.setId();  自增
            wmMaterial.setUserId(user.getUserId());
            wmMaterial.setUrl(url);
            wmMaterial.setType(0);   //(value = "素材类型            0 图片            1 视频")
            wmMaterial.setIsCollection(false); //(value = "是否收藏")
            wmMaterial.setCreatedTime(new Date()); //(value = "创建时间")
            this.save(wmMaterial);
            return ResponseResult.okResult(wmMaterial);
        }

    }

    @Override
    public ResponseResult listByPage(WmMaterialDto dto) {
        //获取当前用户的id
        User user = UserThreadLocalUtil.get();
        if (user==null) {
            //证明没有 登录人  直接返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建 查询条件
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        if (dto.getIsCollection()!=null) {
            //是否收藏
            query.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //隐藏的条件   当前用户只能 看到知己的图片信息
        query.eq(WmMaterial::getUserId,user.getUserId());
        //对查询结果进行排序  采用更新时间倒叙
        query.orderByDesc(WmMaterial::getCreatedTime);
        //构建分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        Page<WmMaterial> page1 = this.page(page, query);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }
}
